<!-- CellTextButtonWithSearch.vue -->
<template>
  <div class="cell-text-button-with-search" :style="columnWidth ? { width: columnWidth } : {}">
    <input
        type="text"
        :value="modelValue"
        @input="handleInput"
        @focus="$emit('focus', $event)"
        @blur="$emit('blur', $event)"
        class="text-input"
    />
    <button @click="openPopup" class="button">...</button>

    <!-- 弹出窗体 -->
    <div v-if="showPopup" class="popup">
      <div class="popup-content">
        <h3>搜索和选择</h3>
        <div class="search-container">
          <input
              v-model="searchQuery"
              placeholder="搜索..."
              class="search-input"
          />
          <button @click="handleSearch" class="search-button">查询</button>
        </div>
        <div class="search-results">
          <div
              v-for="item in searchResults"
              :key="getItemKey(item)"
              @click="selectItem(item)"
              class="search-item"
          >
            {{ getItemDisplayText(item) }}
          </div>
        </div>
        <div class="popup-buttons">
          <button @click="closePopup" class="cancel-button">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  name: 'CellTextButtonWithSearch',
  props: {
    modelValue: String,
    columnWidth: String,
    searchObj: {
      type: Object,
      required: true,
      validator: (obj) => {
        return obj.url && obj.keyField && obj.showField && obj.token;
      }
    }
  },
  emits: ['update:modelValue', 'focus', 'blur', 'input'],
  setup(props, { emit }) {
    const showPopup = ref(false);
    const searchQuery = ref('');
    const searchResults = ref([]);

    const openPopup = () => {
      showPopup.value = true;
      searchQuery.value = '';
      searchResults.value = []; // 清空之前的搜索结果
    };

    const closePopup = () => {
      showPopup.value = false;
    };

    const handleInput = (event) => {
      emit('update:modelValue', event.target.value);
      emit('input', event.target.value);
    };

    const handleSearch = async () => {
      try {
        const fullUrl = `${props.searchObj.url}&query=${encodeURIComponent(searchQuery.value)}`;
        const headers = new Headers({
          'X-Access-Token': props.searchObj.token
        });

        const response = await fetch(fullUrl, {
          method: 'GET',
          headers: headers,
        });

        if (!response.ok) {
          throw new Error('搜索请求失败');
        }
        const data = await response.json();

        if (data.success && data.result) {
          searchResults.value = data.result.records;
        } else {
          throw new Error(data.message || '搜索失败');
        }
      } catch (error) {
        console.error('搜索出错:', error);
        // 这里可以添加错误处理，比如显示一个错误消息
      }
    };

    const getItemKey = (item) => {
      return props.searchObj.keyField.split(';').map(field => item[field]).join('_');
    };

    const getItemDisplayText = (item) => {
      return props.searchObj.showField.split(';').map(field => item[field]).join(' - ');
    };

    const selectItem = (item) => {
      const selectedValue = props.searchObj.keyField.split(';').map(field => item[field]).join(';');
      emit('update:modelValue', selectedValue);
      emit('input', selectedValue);
      closePopup();
    };

    return {
      showPopup,
      searchQuery,
      searchResults,
      openPopup,
      closePopup,
      handleInput,
      handleSearch,
      getItemKey,
      getItemDisplayText,
      selectItem
    };
  }
}
</script>

<style scoped>
.cell-text-button-with-search {
  display: flex;
  align-items: center;
  height: 100%;
  box-sizing: border-box;
}

.text-input {
  flex-grow: 1;
  min-width: 0;
  padding: 2px 4px;
  border: none;
  background: transparent;
  font-size: inherit;
  line-height: inherit;
  height: 100%;
}

.button {
  flex-shrink: 0;
  width: 16px;
  height: 16px;
  padding: 0;
  margin-left: 2px;
  background-color: #f0f0f0;
  border: 1px solid #ccc;
  border-radius: 2px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
}

.popup {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.popup-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 300px;
  max-height: 80vh;
  overflow-y: auto;
}

.search-container {
  display: flex;
  margin-bottom: 10px;
}

.search-input {
  flex-grow: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px 0 0 4px;
}

.search-button {
  padding: 8px 12px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

.search-results {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #eee;
  border-radius: 4px;
}

.search-item {
  padding: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.search-item:hover {
  background-color: #f0f0f0;
}

.popup-buttons {
  margin-top: 10px;
  text-align: right;
}

.cancel-button {
  padding: 6px 12px;
  background-color: #f0f0f0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-button:hover {
  background-color: #e0e0e0;
}
</style>
